package com.example.emos.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.entity.TbUser;
import com.example.emos.wx.exception.EmosException;
import com.example.emos.wx.mapper.TbUserMapper;
import com.example.emos.wx.pojo.dto.UserLoginDTO;
import com.example.emos.wx.pojo.dto.UserRegisterDTO;
import com.example.emos.wx.pojo.vo.UserLoginVO;
import com.example.emos.wx.service.UserService;
import com.example.emos.wx.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Value("${emos.wechat.appid}")
    private String appid;

    @Value("${emos.wechat.secret}")
    private String secret;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private JwtUtil jwtUtil;

    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        String response = HttpUtil.post(url, params);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new EmosException("临时登陆凭证code错误");
        }
        return openId;
    }

    /**
     * 注册用户
     *
     * @param userRegisterDTO
     * @return
     */
    @Override
    public int registerUser(UserRegisterDTO userRegisterDTO) {
        // 注册码000000超级管理员
        // 查询是否有超级管理员
        // 有，报错已经存在超级管理员
        // 无，注册为超级管理员

        if ("000000".equals(userRegisterDTO.getRegisterCode())) {
            boolean haveRootUser = tbUserMapper.haveRootUser();
            if (!haveRootUser) {
                String openId = getOpenId(userRegisterDTO.getCode());
                TbUser user = new TbUser();
                user.setOpenId(openId);
                user.setNickname(userRegisterDTO.getNickname());
                user.setPhoto(userRegisterDTO.getPhoto());
                user.setStatus(1);
                user.setRole("[0]");
                user.setRoot(1);
                user.setCreateTime(new Date());
                tbUserMapper.insert(user);
                int id = tbUserMapper.searchIdByOpenId(openId);
                return id;
            } else {
                throw new EmosException("超级管理员已存在");
            }
        } else {
            // TODO此处还有其他的判断逻辑
            // 查询openid是否已经注册
            // 已注册，报错微信账号已经注册
            // 未注册，查询注册码是否失效
            // 已失效，报错注册码已经过期
            // 未失效，注册为普通用户
            return 0;
        }

    }

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());
        Integer userId = tbUserMapper.searchIdByOpenId(openId);
        String token = jwtUtil.createToken(userId);
        Set<String> userPermissions = tbUserMapper.searchUserPermissions(userId);
        if (userId == null) {
            throw new EmosException("帐户不存在");
        }
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .token(token)
                .permission(userPermissions)
                .build();
        // TODO 从消息队列中接收消息，转移到消息列表
        return userLoginVO;
    }

    /**
     * 查询用户所有权限名
     *
     * @param userId
     * @return
     */
    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = tbUserMapper.searchUserPermissions(userId);
        return permissions;
    }
}
